package com.frxuexi.lib_base

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object DownLoadUtil {
    fun download(url:String,path:File):Flow<IUiState>{
        return flow {
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if(response.isSuccessful){
                response.body.let {body->
                    path.outputStream().let {os->
                        val stream=body?.byteStream()
                        var bufferLen=0
                        var array=ByteArray(DEFAULT_BUFFER_SIZE)
                        while(stream?.read(array).also { bufferLen=it!! }!=-1){
                            os.write(array,0,bufferLen)
                        }
                        os.flush()
                        os.close()
                        emit(IUiState.onSuccess("",RequestType.DOWNLOAD))
                    }
                }
            }else{
                emit(IUiState.onError("没有下载成功"))
            }
        }
    }
}